<template>
  <div class="article-container">
    <van-nav-bar
      class="login-nav-bar"
      left-arrow
      title="黑马头条"
      @click-left="$router.push('/home')"
    ></van-nav-bar>

    <div class="main-wrap">
      <div class="loading-wrap" v-if="isLoading">
        <van-loading
          color="#3296fa"
          vertical
        >加载中</van-loading>
      </div>

      <div class="article-detail" v-else-if="article.title">
        <h1 class="article-title">{{article.title}}</h1>

        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="article.aut_photo"
          />
          <div slot="title" class="user-name">{{article.aut_name}}</div>
          <div slot="label" class="publish-date">{{article.pubdate | relativeTime}}</div>

          <follow-item
            v-model="article.is_followed"
            :user_id="article.aut_id"
          />
        </van-cell>

        <div class="article-content markdown-body" v-html="article.content"></div>
        <van-divider>正文结束</van-divider>

        <!-- 3. 传递文章id -->
        <article-item
          :articleId="articleId"
          @changeTotalCount="total_count = $event"
        />

        <div class="article-bottom">
          <van-button
            class="comment-btn"
            type="default"
            round
            size="small"
            @click="isPostShow = true"
          >写评论</van-button>
          <van-icon
            name="comment-o"
            :badge="total_count"
            color="#777"
          />

          <collect-article
            v-model="article.is_collected"
            :articleId="articleId"
          />

          <like-article
            v-model="article.attitude"
            :articleId="articleId"
          />

          <van-icon name="share" color="#777777"></van-icon>
        </div>
      </div>

      <div class="error-wrap" v-else-if="noId">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>

      <div class="error-wrap" v-else>
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="getArticleByIdFn">点击重试</van-button>
      </div>
    </div>

    <van-popup
      v-model="isPostShow"
      position="bottom"
    >
      <!-- 3. 父组件监听事件， 隐藏弹框 -->
      <article-post
        @changeShow="isPostShow = false"
      />
    </van-popup>

    <van-popup
      v-model="isReplyShow"
      position="bottom"
      style="height: 100%"
    >
      <article-reply
        v-if="isReplyShow"
        :currentComment="currentComment"
        @click-close="isReplyShow = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { getArticleById } from '@/api/article.js'
import { ImagePreview } from 'vant'
import FollowItem from '@/components/follow-item'
import CollectArticle from '@/components/collect-article'
import LikeArticle from '@/components/like-article'
import ArticleItem from '@/components/article-item'
import ArticlePost from '@/components/article-post'
import ArticleReply from '@/components/article-reply'
// 1. 导入中介
import Bus from '@/utils/bus'
import './styles/github-markdown-light.css'

export default {
  name: 'article-box',
  props: ['articleId'],
  components: {
    FollowItem,
    CollectArticle,
    LikeArticle,
    ArticleItem,
    ArticlePost,
    ArticleReply
  },
  created() {
    this.getArticleByIdFn()

    this.getRes()
  },
  data() {
    return {
      article: {},
      isLoading: false,
      noId: false,
      loading: false,
      total_count: 0,
      isPostShow: false,
      isReplyShow: false,
      currentComment: {}
    }
  },
  methods: {
    async getArticleByIdFn() {
      this.isLoading = true
      try {
        if(Math.random() > 0.9) {
          throw new Error('出错了')
        }
        const {data: {data}} = await getArticleById(this.articleId)

        // 1. 因为 后台返回的图片url错误， 所以我们自己提供了图片
        data.content = `<div>
          <h2>我是标题1111</h2>
          <img class="img-item" src="https://img01.yzcdn.cn/vant/apple-1.jpg" alt="">
          <h2>我是标题222</h2>
          <img class="img-item" src="https://img01.yzcdn.cn/vant/apple-2.jpg" alt="">
          <h2>我是标题333</h2>
          <img class="img-item" src="https://img01.yzcdn.cn/vant/apple-3.jpg" alt="">
          ${data.content}
        </div>`

        this.article = data

        // 2. 因为页面更新是异步的  所以 异步调用方法 这样才能获取页面元素
        setTimeout(() => {
          this.priveImg()
        })
      } catch(err) {
        if(err.response && err.response.status === 404) {
          this.noId = true
        }
      }
      this.isLoading = false
    },
    priveImg() {
      // 3. 获取 创建的图片元素
      let arr = document.querySelectorAll('.img-item')

      // 4. 准备 预览图片数组
      let images = []

      // 5. 循环 得到的图片
      arr.forEach((item, startPosition) => {
        // 6. 每一张图片 都把 src 添加到 images里
        images.push(item.src)

        // 7. 给每一个图片注册点击事件
        item.onclick = function() {
          // 8. 调用 vant 实现 预览
          ImagePreview({
            images,    // 预览的图片
            startPosition,   // 预览开始的位置
            closeable: true,  // 关闭按钮
          })
        }
      })
    },
    getRes() {
      // 2. 利用中介 监听孙子的事件
      Bus.$on('reply-click', res => {
        this.isReplyShow = true

        this.currentComment = res
      })
    }
  }
}
</script>

<style scoped lang="less">
.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
